const express = require('express');
const multer = require('multer');
const VolcUploader = require('./services/volcUploader');
const path = require('path');

const app = express();
const upload = multer({ storage: multer.memoryStorage() });
const config = require('./config/config');

// 创建 VolcUploader 实例
const volcUploader = new VolcUploader();

// 允许的图片类型
const ALLOWED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
const ALLOWED_AUDIO_TYPES = ['audio/mpeg', 'audio/wav', 'audio/mp3', 'audio/x-m4a', 'audio/aac'];

app.post('/upload', async (req, res) => {
    try {
        // 检查请求头中的 Content-Type
        if (!req.headers['content-type']?.startsWith('image/')) {
            return res.json({ 
                data: {
                    code: 400,
                    message: '请求头 Content-Type 必须是图片类型',
                    data: null
                }
            });
        }

        // 验证文件类型
        const contentType = req.headers['content-type'];
        if (!ALLOWED_IMAGE_TYPES.includes(contentType)) {
            return res.json({ 
                data: {
                    code: 400,
                    message: '只支持 JPG、PNG、GIF、WEBP 格式的图片',
                    data: null
                }
            });
        }

        // 获取文件扩展名
        const ext = '.' + contentType.split('/')[1].replace('jpeg', 'jpg');
        const fileName = `${Date.now()}-${Math.random().toString(36).substring(7)}${ext}`;
        const key = `images/${fileName}`;

        // 读取二进制数据
        let chunks = [];
        req.on('data', chunk => chunks.push(chunk));
        
        const buffer = await new Promise((resolve, reject) => {
            req.on('end', () => resolve(Buffer.concat(chunks)));
            req.on('error', reject);
        });

        // 上传文件
        const result = await volcUploader.uploadFile(buffer, key);

        if (result.success) {
            res.json({
                data: {
                    code: 0,
                    message: '上传成功',
                    data: {
                        url: result.url,
                        key: result.key
                    }
                }
            });
        } else {
            res.json({
                data: {
                    code: 500,
                    message: result.error,
                    data: null
                }
            });
        }
    } catch (error) {
        console.error('上传失败:', error);
        res.json({
            data: {
                code: 500,
                message: '文件上传失败',
                data: null
            }
        });
    }
});

app.post('/upload-audio', async (req, res) => {
    try {
        // 检查请求头中的 Content-Type
        if (!req.headers['content-type']?.startsWith('audio/')) {
            return res.json({ 
                data: {
                    code: 400,
                    message: '请求头 Content-Type 必须是音频类型',
                    data: null
                }
            });
        }

        // 验证文件类型
        const contentType = req.headers['content-type'];
        if (!ALLOWED_AUDIO_TYPES.includes(contentType)) {
            return res.json({ 
                data: {
                    code: 400,
                    message: '只支持 MP3、WAV、M4A、AAC 格式的音频文件',
                    data: null
                }
            });
        }

        // 获取文件扩展名
        const ext = '.' + contentType.split('/')[1].replace('mpeg', 'mp3');
        const fileName = `${Date.now()}-${Math.random().toString(36).substring(7)}${ext}`;
        const key = `audios/${fileName}`;

        // 读取二进制数据
        let chunks = [];
        req.on('data', chunk => chunks.push(chunk));
        
        const buffer = await new Promise((resolve, reject) => {
            req.on('end', () => resolve(Buffer.concat(chunks)));
            req.on('error', reject);
        });

        // 上传文件
        const result = await volcUploader.uploadFile(buffer, key);

        if (result.success) {
            res.json({
                data: {
                    code: 0,
                    message: '上传成功',
                    data: {
                        url: result.url,
                        key: result.key
                    }
                }
            });
        } else {
            res.json({
                data: {
                    code: 500,
                    message: result.error,
                    data: null
                }
            });
        }
    } catch (error) {
        console.error('音频上传失败:', error);
        res.json({
            data: {
                code: 500,
                message: '音频文件上传失败',
                data: null
            }
        });
    }
});

app.listen(config.port, () => {
    console.log(`Tools service running on port ${config.port}`);
}); 